import { createRouter, createWebHistory } from 'vue-router'
import { ElMessage } from 'element-plus'
import store from '@/store'
import { getToken } from '@/utils/auth'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

// 配置NProgress
NProgress.configure({ 
  showSpinner: false,
  minimum: 0.1,      // 默认最小百分比
  trickleSpeed: 200, // 更新速度
  easing: 'ease',    // 动画效果
  speed: 500,        // 进度条速度
  trickle: true      // 自动递增
})

// 获取页面标题
const getPageTitle = (pageTitle) => {
  const title = '光伏知识图谱管理系统'
  if (pageTitle) {
    return `${pageTitle} - ${title}`
  }
  return title
}

// 公共路由
const publicRoutes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue'),
    meta: { title: '登录' }
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('@/views/Register.vue'),
    meta: { title: '注册' }
  }
]

// 需要认证的路由
const authRoutes = [
  {
    path: '/',
    redirect: '/dashboard'
  },
  {
    path: '/dashboard',
    name: 'Dashboard',
    component: () => import('@/views/dashboard/index.vue'),
    meta: { title: '首页', requiresAuth: true }
  },
  {
    path: '/graph-analysis',
    name: 'GraphAnalysis',
    component: () => import('@/views/GraphAnalysisNew.vue'),
    meta: { title: '知识图谱分析', requiresAuth: true },
    children: [
      {
        path: 'industry-analysis',
        name: 'IndustryAnalysisTab',
        component: () => import('@/views/GraphAnalysisNew.vue'),
        meta: { title: '行业企业综合分析', requiresAuth: true, activeTab: 'industryComprehensive' }
      }
    ]
  },
  {
    path: '/industry-analysis',
    name: 'IndustryAnalysis',
    component: () => import('@/views/IndustryAnalysis.vue'),
    meta: { title: '行业企业综合分析', requiresAuth: true }
  },
  {
    path: '/user-management',
    name: 'UserManagement',
    component: () => import(/* webpackChunkName: "user-management" */ '@/views/UserManagement.vue'),
    meta: { title: '用户权限管理', requiresAuth: true, permissions: ['user:manage'] }
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes: [...publicRoutes, ...authRoutes]
})

// 白名单路由
// const whiteList = ['/login', '/register']

// 路由守卫
router.beforeEach(async (to, from, next) => {
  // 显示加载进度条
  NProgress.start()
  
  // 设置页面标题
  document.title = getPageTitle(to.meta.title)
  
  // 获取token
  const hasToken = getToken()
  
  if (!hasToken) {
    // 未登录
    if (to.path === '/login' || to.path === '/register') {
      // 直接访问登录或注册页
      next()
    } else {
      // 重定向到登录页
      next(`/login?redirect=${to.path}`)
    }
    NProgress.done()
  } else {
    // 已登录
    if (to.path === '/login') {
      // 已登录，跳转到首页
      console.log('已登录状态访问登录页，重定向到首页')
      next({ path: '/' })
    } else {
      // 判断是否已获取用户信息
      const hasUserInfo = store.getters.userInfo && store.getters.userInfo.id
      console.log('用户信息状态:', hasUserInfo ? '已获取' : '未获取')
      
      // 检查权限是否异常
      const hasAnyPermission = store.getters.permissions && store.getters.permissions.length > 0
      console.log('权限状态:', hasAnyPermission ? `已获取(${store.getters.permissions.length}个)` : '无权限')
      
      // 如果已登录但没有任何权限，可能是权限加载问题，尝试强制刷新
      if (hasUserInfo && !hasAnyPermission) {
        console.log('检测到权限异常：用户已登录但没有任何权限，尝试强制刷新...')
        try {
          await store.dispatch('getUserInfo', true)
          console.log('强制刷新权限成功，继续路由...')
        } catch (error) {
          console.error('强制刷新权限失败:', error)
          // 即使失败也继续后续处理
        }
      }
      
      if (hasUserInfo) {
        // 检查权限
        if (to.meta.permissions) {
          const hasPermission = store.getters.hasPermission(to.meta.permissions)
          console.log('权限检查:', to.meta.permissions, hasPermission ? '有权限' : '无权限')
          if (hasPermission) {
            next()
          } else {
            ElMessage.error('您没有访问权限，请联系管理员授权')
            next('/dashboard')
          }
        } else {
          // 知识图谱分析页面特殊处理，允许admin用户访问
          if (to.path === '/graph-analysis') {
            // 检查是否为admin用户
            const userInfo = store.getters.userInfo
            if (userInfo && userInfo.username === 'admin') {
              console.log('[Router] admin用户访问知识图谱分析页面，直接放行')
              next()
              return
            }
            
            // 非admin用户检查是否有图谱权限
            const hasGraphPerm = store.getters.hasAnyGraphPermission
            console.log('[Router] 非admin用户访问知识图谱分析页面，权限检查结果:', hasGraphPerm)
            if (hasGraphPerm) {
              next()
            } else {
              ElMessage.error('您没有知识图谱分析权限，请联系管理员授权')
              next('/dashboard')
            }
          } else {
            next()
          }
        }
      } else {
        try {
          // 获取用户信息
          console.log('尝试获取用户信息')
          await store.dispatch('getUserInfo', true)  // 修改为始终强制刷新
          console.log('获取用户信息成功')
          
          // 检查权限
          if (to.meta.permissions) {
            const hasPermission = store.getters.hasPermission(to.meta.permissions)
            console.log('权限检查:', to.meta.permissions, hasPermission ? '有权限' : '无权限')
            if (hasPermission) {
              next()
            } else {
              ElMessage.error('您没有访问权限，请联系管理员授权')
              next('/dashboard')
            }
          } else {
            next()
          }
        } catch (error) {
          // 获取用户信息失败，清除token并跳转到登录页
          console.error('获取用户信息失败:', error)
          await store.dispatch('resetToken')
          ElMessage.error(error.message || '验证失败，请重新登录')
          next(`/login?redirect=${to.path}`)
        }
      }
    }
  }
  NProgress.done()
})

// 全局后置钩子，确保进度条完成
router.afterEach(() => {
  // 完成进度条
  NProgress.done()
})

export default router 